/**
 * Created by lucas on 2017/3/19.
 */
"use strict";

import React, {Component, PropTypes} from 'react';
import classNames from 'classnames';

export default class Rating extends Component {

    static propTypes = {
        defaultValue: PropTypes.number,
        readonly: PropTypes.bool,
        max: PropTypes.number,
    }

    static defaultProps = {
        defaultValue: 0,
        max: 5,
    }

    state = {
        rating: this.props.defaultValue, // 当前显示的评分。
        tmpRating: this.props.defaultValue, // 用户把鼠标放在星星上移动但尚未点击提交时显示的评分。
    }

    getValue() {
        return this.state.rating;
    }

    // 鼠标移动到组件上。
    setTemp(rating) {
        this.setState({
            tmpRating: rating,
        })
    }

    // 点击组件时候
    setRating(rating) {
        this.setState({
            tmpRating: rating,
            rating: rating,
        });
    }

    // 鼠标移开时。
    reset() {
        this.setTemp(this.state.rating);
    }

    // 响应外部变化。
    componentWillReceiveProps(nextProps) {
        this.setRating(nextProps.defaultValue);
    }

    render() {
        const starts = [];
        for (let index = 1; index <= this.props.max; index++) {
            starts.push(
                <span key={index}
                      className={index <= this.state.tmpRating ? 'RatingOn': null}
                      onClick={!this.props.readonly && this.setRating.bind(this, index)}
                      onMouseOver={!this.props.readonly && this.setTemp.bind(this, index)}
                >
                    &#9734;
                </span>
            );
        }

        return (
            <div className={
                classNames({
                    'Rating': true,
                    'RatingReadonly': this.props.readonly
                })}
                 onMouseOut={this.reset.bind(this)}>
                {starts}
                {
                    this.props.readonly || !this.props.id
                        ? null
                        : <input
                            type="hidden"
                            id={this.props.id}
                            value={this.state.rating} />
                }
            </div>
        )
    }
}